<template>
	<view class="IM">
		<scroll-view :scroll-top="scrollTop" scroll-y="true" class="IM-box" :scroll-into-view="scroll_id">
			<view class="msg-box" :style="'padding-bottom:'+ paddingBtm + 'px;'">
				<view class="item" v-for="(item,index) in messageList" :key="index" :id="'msg' + item.sequence" @click="onFalse">
					<view class="item-left" v-if="item.flow == 'in'">
						<!-- <image :src="item.avatar" mode="" v-if="item.avatar.length == 0"></image> -->
						<image :src="head_pic" mode=""></image>
						<view class="user-right">
							<text>{{nickname}}</text>
							<!-- 文本消息 -->
							<view class="message" v-if="item.type == 'TIMTextElem'" v-html="mateEmoji(item.payload.text)">
								<!-- {{item.payload.text}} -->
								<!-- {{mateEmoji(item.payload.text)}} -->
							</view>
							<!-- 图片消息 -->
							<view class="message" v-if="item.type == 'TIMImageElem'" @click="onLookImg(item.payload.imageInfoArray[0].imageUrl)">
								<image :src="item.payload.imageInfoArray[1].imageUrl" :style="'width:'+ item.payload.imageInfoArray[1].width +'rpx;max-width:500rpx'"
								 mode="widthFix"></image>
							</view>
							<!-- 自定义商品消息 -->
							<view class="message" v-if="item.type == 'TIMCustomElem' && item.payload.description == 'wares'">
								<view class="goods-info" @click="goGoodsDetail(item.payload.data)">
									<image :src="JSON.parse(item.payload.data).goods_pic" mode=""></image>
									<view class="info-right">
										<text>{{JSON.parse(item.payload.data).goods_name}}</text>
										<text>¥{{JSON.parse(item.payload.data).goods_prices}}</text>
									</view>
								</view>
							</view>
							<!-- 自定义订单消息 -->
							<view class="message" v-if="item.type == 'TIMCustomElem' && item.payload.description == 'order'">
								<view class="goods-info" @click="goOrderDetail(item.payload.data)">
									<image :src="JSON.parse(item.payload.data).pic" mode=""></image>
									<view class="info-right">
										<text>订单编号:{{JSON.parse(item.payload.data).order_sn}}</text>
										<text>¥{{JSON.parse(item.payload.data).prices}}</text>
									</view>
								</view>
							</view>
							<view class="time">
								{{formatDate(item.time)}}
							</view>
						</view>
					</view>
					<view class="item-right" v-if="item.flow == 'out'">
						<view class="user-left">
							<text>{{user_Data.nickName}}</text>
							<!-- 文本消息 -->
							<view class="message" v-if="item.type == 'TIMTextElem'" v-html="mateEmoji(item.payload.text)">
								<!-- {{item.payload.text}} -->
							</view>
							<!-- 语音消息 -->
							<view class="message" v-if="item.type == 'TIMSoundElem'" @click.top="onPay(item.payload.url,index,item.payload.second)">
								{{item.payload.second}}"
								<image src="../../../static/is_laba.gif" mode="widthFix" v-if="index == is_laba" style="width: 23upx;"></image>
								<image src="../../../static/is_laba.png" mode="widthFix" v-else style="width: 23upx;"></image>
							</view>
							<!-- 图片消息 -->
							<view class="message" v-if="item.type == 'TIMImageElem'" @click="onLookImg(item.payload.imageInfoArray[0].imageUrl)">
								<image :src="item.payload.imageInfoArray[1].imageUrl" :style="'width:'+ item.payload.imageInfoArray[1].width +'rpx;max-width:500rpx'"
								 mode="widthFix"></image>
							</view>
							<!-- 视频 -->
							<view class="message" v-if="item.type == 'TIMVideoFileElem'">
								<video :src="item.payload.videoUrl" controls style="max-width: 500upx;"></video>
							</view>
							<view class="time">
								{{formatDate(item.time)}}
							</view>
						</view>
						<image :src="user_Data.avatarUrl" mode="" class="headImg"></image>
					</view>
				</view>
			</view>

		</scroll-view>
		<!-- 底层输入框 -->
		<view class="input-box">
			<view class="input-top">
				<u-icon name="mic" style="margin-bottom: 30upx;" color="#999" size="50" @click.stop="onVoice"></u-icon>
				<view class="input">
					<input type="text" v-model="msgContent" @confirm.stop="onMessage" />
					<image src="../../../static/haoping.png" mode="" @click="onEmoji"></image>
				</view>
				<u-icon name="plus-circle-fill" color="#D1AA56" style="margin-bottom: 30upx;z-index: 10;" size="56" @click.stop="onMedia"></u-icon>
			</view>
			<view class="center" :class="{displaynone:!voiceShow}">
				<view class="box">
					<view class="item">
						<u-icon name="mic" color="#fff" size="50" @touchstart="startVoice" @touchend="stopVoice"></u-icon>
					</view>
				</view>
			</view>
			<view class="emoji" :class="{displaynone:!emojiShow}">
				<view class="box">
					<view class="item" v-for="(item,index) in emojiMap" :key="index" @click="inputEmoji(index)">
						<image :src="emojiUrl + item" mode="widthFix"></image>
					</view>
				</view>
			</view>
			<view class="medias" :class="{displaynone:!mediaShow}">
				<view class="box">
					<view class="item" @click="onPhoto">
						<u-icon name="photo" color="#999" size="60"></u-icon>
						<text>相册</text>
					</view>
					<view class="item" @click="onCamera">
						<u-icon name="camera" color="#999" size="60"></u-icon>
						<text>拍照</text>
					</view>
					<view class="item" @click="onVideo">
						<u-icon name="play-right" color="#999" size="60"></u-icon>
						<text>视频</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	// 引入im
	import TIM from 'tim-wx-sdk';
	import COS from "cos-wx-sdk-v5";
	import {
		emojiUrl,
		emojiMap,
		emojiName
	} from '../../../utils/emojiMap.js';
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	export default {
		data() {
			return {
				user_info: {},
				tim: '',
				scrollTop: 0,
				messageList: [],
				user_Data: uni.getStorageSync('user_info'),
				msgContent: '', //文字消息内容
				scroll_id: '',
				voiceShow: false, //语音消息
				emojiShow: false,
				mediaShow: false,
				zhanwei: '100rpx',
				paddingBtm: '50',
				voicePath: '', //语音消息
				is_laba: '',
				emojiUrl: emojiUrl,
				emojiMap: emojiMap,
				emojiName: emojiName,
				service_account:'',//默认客服id
				head_pic:'',//默认客服头像
				nickname:'',
				bigImg:'',
				msgNum:0
			};
		},
		onUnload() {
			this.setMessageRead()
			let num = uni.getStorageSync('msgNum')
			num = num - this.msgNum
			uni.setStorageSync('msgNum')
		},
		onShow() {

		},
		created() {
			setTimeout(()=>{
				console.log(this.messageList);
			},5000)
		},
		onLoad(option) {
			this.service_account = option.id
			console.log('客服ID' + this.service_account)
			let service_data = uni.getStorageSync('service_data')
			
			this.head_pic = service_data.head_pic
			
			this.nickname = service_data.nickname
			
			this.bigImg = service_data.service_pic
			this.getMessageList()
			this.setMessageRead()
			let num = parseInt(uni.getStorageSync('msgNum')) - parseInt(option.num)
			uni.setStorageSync('msgNum')
			this.onMessageList()
		},
		methods: {
			// 消息已读
			setMessageRead(){
				// 将某会话下所有未读消息已读上报
				let promise = this.$tim.setMessageRead({conversationID: 'C2C' + this.service_account});
				promise.then(function(imResponse) {
				  // 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
				  console.log('已读成功')
				}).catch(function(imError) {
				  // 已读上报失败
				  console.warn('setMessageRead error:', imError);
				});
			},
			// 关闭输入款
			onFalse(){
				this.voiceShow = false
				this.emojiShow = false
				this.mediaShow = false
				this.paddingBtm = '50'
			},
			// 监听消息
			onMessageList(){
				this.$tim.on(TIM.EVENT.MESSAGE_RECEIVED, (event) => {
					// 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
					console.log(event.data);
					this.msgNum ++
					for (let i = 0; i < event.data.length; i++) {
						if(event.data[i].type == 'TIMTextElem'){
							this.messageList = this.messageList.concat(event.data[i])
						}
					}
					for (var i = 0; i < this.messageList.length; i++) {
						this.messageList[i]
					}
					const this_ = this
					this.$nextTick(() => {
						this_.scroll_id = 'msg' + this_.messageList[i - 1].sequence
					})
				})

			},
			// 发送视频
			onVideo(){
				uni.chooseVideo({
					maxDuration:60,
					camera:'back',
					success: (res) => {
						let message = this.$tim.createVideoMessage({
						  to: this.service_account,
						  conversationType: TIM.TYPES.CONV_C2C,
						  payload: {
							file: res
						  },
						  onProgress: function(event) { console.log('video uploading:', event) }
						})
						// 3. 发送消息
						let promise = this.$tim.sendMessage(message);
						promise.then((e)=> {
						 // 发送成功
						 this.messageList = this.messageList.concat(e.data.message)
						 console.log(this.messageList)
						 const this_ = this
						 this.$nextTick(() => {
						 	let lng = this_.messageList.length
						 	this_.scroll_id = 'msg' + this_.messageList[lng - 1].sequence
						 })
						 this.onFalse()
						}).catch((err)=> {
						  // 发送失败
						  uni.showToast({
						  	title:'只支持mp4格式',
						  	icon:'none',
						  	duration:1200
						  })
						});
					}
				})
			},
			// 打开相机
			onCamera() {
				uni.chooseImage({
					sourceType: ['camera'],
					success: (res) => {
						this.sendImage(res)
					},
					fail: (err) => {
						uni.showToast({
							title:err
						})
					}
				})
			},
			// 预览图片
			onLookImg(url) {
				console.log(url)
				uni.previewImage({
					urls: [url]
				})
			},
			// 发送图片
			sendImage(res) {
				let message = this.$tim.createImageMessage({
					to: this.service_account,
					conversationType: TIM.TYPES.CONV_C2C,
					payload: {
						file: res
					},
					onProgress: (event) => {
						console.log('file uploading:', event)
					}
				});
				// 3. 发送图片
				let promise = this.$tim.sendMessage(message);
				promise.then((e) => {
					// 发送成功
					this.messageList = this.messageList.concat(e.data.message)
					console.log(this.messageList)
					const this_ = this
					this.$nextTick(() => {
						let lng = this_.messageList.length
						this_.scroll_id = 'msg' + this_.messageList[lng - 1].sequence
					})
					this.onFalse()
				}).catch((err) => {
					// 发送失败
					uni.showToast({
						title:err
					})
					console.warn('sendMessage error:', err);
				});
			},
			// 选择相册
			onPhoto() {
				uni.chooseImage({
					sourceType: ['album'],
					count: 1,
					success: (res) => {
						this.sendImage(res)
					}
				})
			},
			// 显示多媒体
			onMedia() {
				this.emojiShow = false
				this.voiceShow = false
				this.mediaShow = !this.mediaShow
				if (this.mediaShow == false) {
					this.paddingBtm = '50'
				} else {
					this.paddingBtm = '260'
				}
				this.goBtm()
			},
			// 点击表情
			inputEmoji(index) {
				this.msgContent = this.msgContent + index
			},
			// 显示表情列表
			onEmoji() {
				this.mediaShow = false
				this.voiceShow = false
				this.emojiShow = !this.emojiShow
				if (this.emojiShow == false) {
					this.paddingBtm = '50'
				} else {
					this.paddingBtm = '260'
				}
				this.goBtm()
			},
			// 匹配表情文字转化表情
			mateEmoji(val) {
				let reg = '\\[{1}(.+)]'
				if (val.match(reg) !== null) {
					let url = ''
					let imgName = val.match(reg)[0]
					url = emojiUrl + emojiMap[imgName]
					const html = '<img src="' + url + '" style="width:24px;hegiht:24px"/>'
					val = val.replace(imgName, html)

				}
				return val

			},
			// 播放音频
			onPay(url, index, num) {
				this.is_laba = index
				innerAudioContext.src = url;
				innerAudioContext.onPlay(e => {
					console.log(e)
				})
				setTimeout(() => {
					this.is_laba = ''
				}, (num + 1) * 1000)
			},
			// 结束录音
			stopVoice() {
				uni.hideLoading()
				recorderManager.stop();
				// 返回的录音文件
				recorderManager.onStop((res) => {
					const msg = this.$tim.createAudioMessage({
						to: this.service_account,
						conversationType: TIM.TYPES.CONV_C2C,
						payload: {
							file: res
						}
					});
					// 5. 发送消息
					let promise = this.$tim.sendMessage(msg);
					promise.then((e) => {
						this.messageList = this.messageList.concat(e.data.message)
						const this_ = this
						this.$nextTick(() => {
							let lng = this_.messageList.length
							this_.scroll_id = 'msg' + this_.messageList[lng - 1].sequence
						})
					})
				});
			},
			// 开始录取音频
			startVoice() {
				uni.showLoading({
					title: '松开手指发送',
				})
				const options = {
					sampleRate: 44100, // 采样率
					numberOfChannels: 1, // 录音通道数
					encodeBitRate: 192000, // 编码码率
					format: 'aac' // 音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和Web）互通
				}
				recorderManager.start(options);
			},
			// 滚动到底部
			goBtm() {
				this.scroll_id = ''
				this.$nextTick(() => {
					let len = this.messageList.length - 1
					this.scroll_id = 'msg' + this.messageList[len].sequence
				})
			},
			// 显示操作语音
			onVoice() {
				this.emojiShow = false
				this.mediaShow = false
				this.voiceShow = !this.voiceShow
				if (this.voiceShow == false) {
					this.paddingBtm = '50'
				} else {
					this.paddingBtm = '260'
				}
				this.goBtm()
			},
			// 跳转到订单详情页面
			goOrderDetail(data) {
				let id = JSON.parse(data).order_item_ids
				uni.navigateTo({
					url: '../orderDetail/orderDetail?id=' + id
				})
			},
			// 跳转到商品详情页面
			goGoodsDetail(data) {
				// console.log(data)
				let id = JSON.parse(data).goods_id
				uni.navigateTo({
					url: '../shop/goodsDetail/goodsDetail?id=' + id
				})
			},
			// 转化时间戳
			formatDate(value) {
				let time = new Date(value * 1000)
				let year = time.getFullYear()
				let month = time.getMonth() + 1
				let date = time.getDate()
				let hours = time.getHours()
				let minute = time.getMinutes()
				let second = time.getSeconds()
				if (month < 10) {
					month = '0' + month
				}
				if (date < 10) {
					date = '0' + date
				}
				if (hours < 10) {
					hours = '0' + hours
				}
				if (minute < 10) {
					minute = '0' + minute
				}
				if (second < 10) {
					second = '0' + second
				}
				return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
			},
			// 获取消息列表
			getMessageList() {
				// 打开某个会话时，第一次拉取消息列表
				let promise = this.$tim.getMessageList({
					conversationID: 'C2C'+this.service_account,
					count: 40
				});
				promise.then((res) => {
					const messageList = res.data.messageList; // 消息列表。
					const nextReqMessageID = res.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
					const isCompleted = res.data.isCompleted; // 表示是否已经拉完所有消息。
					this.messageList = messageList
					console.log(this.messageList);
					for (var i = 0; i < this.messageList.length; i++) {
						this.messageList[i]
					}
					const this_ = this
					this.$nextTick(() => {
						this_.scroll_id = 'msg' + this_.messageList[i - 1].sequence
					})
				});
			},
			//发送消息
			onMessage() {
				// 创建文本消息
				let message = this.$tim.createTextMessage({
					to: this.service_account,
					conversationType: TIM.TYPES.CONV_C2C,
					payload: {
						text: this.msgContent
					}
				})
				// 2. 发送消息
				let promise = this.$tim.sendMessage(message);
				promise.then((res) => {
					// 发送成功
					console.log(res);
					this.msgContent = ''
					this.getMessageList()
				}).catch((err) => {
					// 发送失败
					uni.showToast({
					    title:'接收方ID无效',
					    icon:'none',
					    duration:1200
					})
					console.warn('发送失败', err);
				});

			}
		}
	}
</script>

<style lang="scss" scoped>
	.IM {
		width: 100vw;
		min-height: 100vh;
		background-color: #fff;

		.IM-box {
			height: 100vh;
			width: calc(100vw - 60upx);
			padding: 30upx;

			.msg-box {
				position: relative;
				.item {
					.item-left {
						display: flex;
						margin-bottom: 70upx;
						position: relative;

						>image {
							width: 75upx;
							height: 75upx;
							border-radius: 50%;
							margin-right: 20upx;
						}

						.user-right {
							display: flex;
							flex-direction: column;
							justify-content: flex-start;
							align-items: flex-start;

							text {
								font-size: 22upx;
								color: #666;
								margin-bottom: 10upx;
							}

							.message {
								background-color: #f7f7f7;
								padding: 25upx;
								border-radius: 20upx;
								border-top-left-radius: 0upx;
								font-size: 26upx;
								color: #333;

								.goods-info {
									display: flex;
									align-items: center;
									background-color: #fff;
									padding: 10upx;

									image {
										width: 100upx;
										height: 100upx;
										margin-right: 15upx;
									}

									.info-right {
										display: flex;
										flex-direction: column;

										text:first-child {
											color: #333;
											font-size: 26upx;
											margin-bottom: 15upx;
											max-width: 380upx;
											overflow: hidden;
											-webkit-line-clamp: 1;
											text-overflow: ellipsis;
											display: -webkit-box;
											-webkit-box-orient: vertical;
										}

										text:last-child {
											font-size: 26upx;
											color: red;
										}
									}

								}
							}

						}

						.time {
							position: absolute;
							bottom: -34upx;
							left: 100upx;
							color: #999;
							font-size: 20upx;
						}
					}

					.item-right {
						display: flex;
						// align-items: flex-end;
						justify-content: flex-end;
						margin-bottom: 70upx;
						width: 100%;
						position: relative;

						.user-left {
							display: flex;
							flex-direction: column;
							justify-content: flex-end;
							align-items: flex-end;

							text {
								font-size: 22upx;
								color: #666;
								margin-bottom: 10upx
							}

							.message {
								background-color: $zhuti-color;
								padding: 25upx;
								border-radius: 20upx;
								border-top-right-radius: 0upx;
								font-size: 26upx;
								color: #fff;
								display: flex;
								align-items: center;
							}
						}

						.time {
							position: absolute;
							right: 100upx;
							bottom: -40upx;
							color: #999;
							font-size: 20upx;
						}

						.headImg {
							width: 75upx;
							height: 75upx;
							border-radius: 50%;
							margin-left: 20upx;
						}
					}

				}
			}

		}

		.displaynone {
			display: none;
		}

		.input-box {
			min-height: 105upx;
			background-color: #fff;
			position: fixed;
			z-index: 100;
			bottom: 0;
			left: 0;
			width: 100%;

			.input-top {
				border-top: 1upx solid #e8e8e8;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 30upx 15upx;
				
				.input {
					position: relative;
					input {
						width: 584upx;
						height: 64upx;
						border: 1upx solid #555;
						border-radius: 60upx;
						color: #333;
						font-size: 26upx;
						margin-bottom: 30upx;
						padding-left: 30upx;
					}

					image {
						position: absolute;
						right: 10upx;
						top: 10upx;
						width: 46upx;
						height: 46upx;
						z-index: 10000;
					}
				}
			}

			.center {
				.box {
					width: 100vw;
					height: 400upx;
					display: flex;
					align-items: center;
					justify-content: center;

					.item {
						width: 100upx;
						height: 100upx;
						background-color: $zhuti-color;
						display: flex;
						align-items: center;
						justify-content: center;
						border-radius: 50%;
					}
				}
			}

			.emoji {
				.box {
					width: 100vw;
					height: 400upx;
					display: flex;
					align-items: center;
					flex-wrap: wrap;
					padding: 0 30upx;
					overflow: scroll;
					.item {
						margin-right: 20upx;
						margin-bottom: 20upx;
						display: flex;
						align-items: center;
						justify-content: center;

						image {
							width: 50upx;
							height: 50upx;
						}
					}
				}
			}

			.medias {
				.box {
					width: 100vw;
					height: 400upx;
					display: flex;
					padding: 30upx;

					.item {
						display: flex;
						justify-content: center;
						flex-direction: column;
						margin-right: 40upx;
						margin-left: 40upx;

						text {
							color: #999;
							font-size: 30upx;
							margin-top: 10upx;
						}
					}
				}
			}
		}

	}
</style>
